package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Measurement;
import model.Sensor;
import DAO.MeasurementsDao;
import DAO.SensorDao;
import database.DBManager;

/**
 * Servlet implementation class SensorServlet
 */
public class SensorServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private DBManager myDb;
	private Connection connection;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SensorServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void init( ServletConfig servletconfig ) {
		// Initialisatie
		myDb = ( DBManager ) servletconfig.getServletContext().getAttribute( "dbmanager" );
		connection = ( Connection ) servletconfig.getServletContext().getAttribute( "connection" );
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher view = null;
		String[] url = request.getQueryString().split( "=" );
		//1	beweging
		//2	lamp
		//3	deur
		//4	temperatuur
		//5	luchtvochtigheid
		//6 lichtsterkte
		if(!isLoggedIn(request)){
			view = request.getRequestDispatcher("index.jsp");
		}else{
			Logger.createLog(request);
			if(url[0].equals("page") && url[1].equals("home")){
				getWarningInfo(request);
				view = request.getRequestDispatcher( "/WEB-INF/home.jsp" );
				}else {
					view = request.getRequestDispatcher( "index.jsp" );
				}
		}
		request = getWarningInfo(request);
		view.forward( request, response );
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher view = null;
		String[] url = request.getQueryString().split( "=" );
		if(!isLoggedIn(request)){
			view = request.getRequestDispatcher("index.jsp");
		}else{
			Logger.createLog(request);
			if(url[0].equals("page") && url[1].equals("lamp")){
				try {
					Sender sender = connection.getSender();
					sender.send((byte)1);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			request.setAttribute("url", "SensorServlet?page=home");
			view = request.getRequestDispatcher( "/WEB-INF/redirect.jsp" );
		}
		request = getWarningInfo(request);
		view.forward( request, response );
	}
	
	private boolean isLoggedIn(HttpServletRequest request){
		HttpSession session = request.getSession();
		boolean loggedIn = false;
		if(session.getAttribute("logged") != null){
			if(session.getAttribute("logged").equals("true")){
				loggedIn = true;
			}
		}
		return loggedIn;
	}
	
	private HttpServletRequest getWarningInfo(HttpServletRequest request){
		MeasurementsDao md = new MeasurementsDao(myDb);
		ArrayList<Measurement> latestMeasurements = new ArrayList<Measurement>();
		for(int i = 1; i <= 5; i++){
			Measurement measurement = md.getLatestMeasurementByID(i);
			if(measurement != null){
				latestMeasurements.add(measurement);
			}
		}
		SensorDao sdao = new SensorDao(myDb);
		ArrayList<Sensor> sensors = sdao.getSensors();
		request.setAttribute("sensorsmax", sensors);
		request.setAttribute("latestMeasurements", latestMeasurements);
		return request;
	}
}
